﻿using BarManager.Core.Common;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.DependencyResolution
{
    public class StructureMapServiceLocator : IServiceLocator
    {
        public T GetService<T>()
        {
            try
            {
                return ObjectFactory.GetInstance<T>();
            }
            catch (Exception ex)
            {
                Debug.Print("GetService<T>: Ex{0} \n\r, Stack:{1}", ex.Message, ex.StackTrace);
                return default(T);
            }
        }

        public object GetService(Type type)
        {
            try
            {
                return ObjectFactory.GetInstance(type);                
            }
            catch (Exception ex)
            {
                Debug.Print("GetService(Type type): Ex{0} \n\r, Stack:{1}", ex.Message, ex.StackTrace);
                return null;
            }
        }

        public IEnumerable<T> GetServices<T>()
        {
            return ObjectFactory.GetAllInstances<T>();
        }

        public IEnumerable<object> GetServices(Type type)
        {
            var result = ObjectFactory.GetAllInstances(type);
            if (result.Count > 0)
                return result.AsQueryable().Cast<object>().AsEnumerable();
            return new List<object>();
        }
    }
}
